package entity

import (
	"fmt"

	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/workflow"
	"shqsoft.cn/pasnj/workflow/entity"

	"github.com/jinzhu/gorm"
	//log "github.com/sirupsen/logrus"
)

//流程运行
type LCYX struct {
	ID     int    `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	LCMC   string `gorm:"column:流程名称"`
	SQSJ   string `gorm:"column:申请时间"`
	SQR    string `gorm:"column:申请人"`
	DQZB   string `gorm:"column:当前在办"`
	DQZT   string `gorm:"column:当前状态"`
	WJSJ   string `gorm:"column:完结时间"`
	RDBGRQ string `gorm:"column:认定变更日期"`
	EMID   int    `gorm:"column:EMID"`
	RUNID  int    `gorm:"column:RUNID"`
	// STEPID int       `gorm:"column:STEPID"`
	FRID int `gorm:"column:FRID"`

	UID      int     `gorm:"column:UID"`
	Progress float64 `gorm:"-" json:"progress"`
	StepName string  `gorm:"-" json:"stepName"`
	Status   string  `gorm:"-" json:"status"`
	STEP     int     `gorm:"-" json:"step"`
}

//TableName Role 流程运行
func (LCYX) TableName() string {
	return "V_FLOW_RUN_STEP"
}

// AfterFind 查询后触发器
func (i *LCYX) AfterFind(tx *gorm.DB) (err error) {
	if i.FRID == 0 {
		i.Status = "exception"
		i.StepName = "校验错误"
		return
	}
	run := entity.FlowRun{}
	if err = tx.Find(&run, i.FRID).Error; err != nil {
		tx.Rollback()
		return
	}
	wf := workflow.GetWorkFlow(run.WFID)
	if wf == nil {
		return fmt.Errorf("指定的流程ID:%d在流程配置中不存在！", run.WFID)
	}
	act := wf.GetAction(run.Step)
	if act == nil {
		return fmt.Errorf("指定的stepID:%d在流程%s配置中不存在！", run.Step, wf.Name)
	}
	count := len(wf.Actions)
	i.STEP = run.Step
	i.StepName = "审批中"
	if i.STEP == 1 {
		i.StepName = "申请中"
	}
	i.Progress = float64(act.Step*100) / float64(count)
	if i.Progress >= 100 && run.State == "0" {
		i.Progress = 95
	}
	i.Status = ""
	if run.State == "0" {
		i.Status = "active"
	} else if run.State == "2" {
		i.StepName = "已中止"
		i.Status = "exception"
	} else {
		i.StepName = "已完成"
		i.Status = "success"
	}
	return
}

func LCYXEF() base.EntityFunc {
	return func() interface{} {
		entity := LCYX{}
		return &entity
	}
}
func LCYXESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []LCYX
		return &entities
	}
}

func init() {
	base.DaoPoolObj.Put("LCYX", base.NewDefaultDao(LCYXEF(), LCYXESF(), nil))
}
